import React from 'react';
import styled from 'styled-components';
import classes from '../helpers/classes';
import useDidMount from '../hooks/useDidMount';
import useGlobalState from '../global';

const Svg = styled.svg`
  width: 1em;
  height: 1em;
  vertical-align: -0.15em;
  fill: currentColor;
  overflow: hidden;
`;

interface IconProps extends React.SVGAttributes<SVGElement> {
  type: string
}

const Icon: React.FC<IconProps> =
  ({
     className = '',
     type,
     ...restProps
   }) => {
    const {globalState, setGlobalState} = useGlobalState();
    // 加载script
    useDidMount(() => {
      if (!globalState.iconListLoaded) {
        console.log('加载iconfont');
        const iconfont = document.createElement('script');
        iconfont.src = '//at.alicdn.com/t/font_1677345_nkcnbo4gr5.js';
        document.head.appendChild(iconfont);
        setGlobalState(draft => {
          draft.iconListLoaded = true;
        });
      }
    });
    // 这里Icon组件是一个SVG元素，所以相对HTMLAttributes 更应该用 SVGAttributes
    return (
      <Svg className={classes(className)}
           {...restProps}>
        <use xlinkHref={`#i${type}`}/>
      </Svg>
    );
  };

export default Icon;